package com.egg.logger.service.access.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.egg.common.mybatis.service.impl.BaseServiceImpl;
import com.egg.common.util.JsonUtil;
import com.egg.logger.entity.access.Access;
import com.egg.logger.mapper.access.AccessMapper;
import com.egg.logger.model.request.AccessPost;
import com.egg.logger.service.access.IAccessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * <p>
 * 访问表 服务实现类
 * </p>
 *
 * @author east
 */
@Slf4j
@Service
public class AccessServiceImpl extends BaseServiceImpl<AccessMapper, Access> implements IAccessService {


    @Override
    public Page<Access> page(
            Integer current, Integer pageSize
            , Optional<Long> userId
            , Optional<String> createDateFrom
            , Optional<Integer> createDateTo
    ) {
        LambdaQueryWrapper<Access> qw = buildLambdaSortQw();
        qw.select(
                Access::getId
                , Access::getRemark
                , Access::getCreateDate
                , Access::getUserId
                , Access::getClientIp
                , Access::getServerIp
                , Access::getMethod
                , Access::getPath
        );
        userId.ifPresent(o -> qw.eq(Access::getUserId, o));
        createDateFrom.ifPresent(o -> qw.ge(Access::getCreateDate, o));
        createDateTo.ifPresent(o -> qw.le(Access::getCreateDate, o));
        return page(new Page<>(current, pageSize), qw);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Long add(AccessPost add) {
        Access access = JsonUtil.objToObj(add, Access.class);
        baseSave(access);
        return access.getId();
    }
}
